/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package be.wiim;

import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

/**
 *
 * @author wim
 */
public class HudsonController {

    static HudsonController fHudsonController;
    String fHudsonUrl;
    String fHudsonJob;
    HudsonJob fHudsonLatestJob;
    
    public HudsonController(String pHudsonUrl, String pHudsonJob) {
        fHudsonUrl = pHudsonUrl;
        fHudsonJob = pHudsonJob;
        fHudsonController = this;
    }
    
    static HudsonController getInstance()
    {
        return fHudsonController;
    }
    
    public HudsonJob getfHudsonLatestJob()
    {
        return latestStatusOfJob();
    }
    
    public HudsonJob latestStatusOfJob()
    {
        URL vUrl = null;
        try {
            vUrl = new URL("http://"+fHudsonUrl+"/api/xml");
            Document vDocument = new SAXReader().read(vUrl);
            for( Element job : (List<Element>)vDocument.getRootElement().elements("job")) 
            {
                if(fHudsonJob.equals(job.elementText("name")))
                    return new HudsonJob(job.elementText("name"),job.elementText("color"));
            }
        } catch (MalformedURLException ex) {
            Logger.getLogger(HudsonController.class.getName()).log(Level.SEVERE, null, ex);
        } catch (DocumentException ex) {
            Logger.getLogger(HudsonController.class.getName()).log(Level.SEVERE, null, ex);
        }
        return null;
    }
    
    public boolean startJob()
    {
        try
        {
            String vUrl = "http://" +fHudsonUrl+"/job/"+fHudsonJob+"/build?delay=0sec";
            URL url = new URL(vUrl);
            URLConnection conn = url.openConnection();
            InputStream is = conn.getInputStream();
        }
        catch(IOException ex)
        {
            ex.printStackTrace();
            return false;
        }
        return true;
    }
    
}
